package com.endoc.phtotapplication;


import android.app.Application;
import android.content.Context;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.nfc.Tag;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.endoc.phtotapplication.litepal.Person;
import com.endoc.phtotapplication.litepal.UploadPerson;
import com.endoc.phtotapplication.network.api.FaceInterface;
import com.endoc.phtotapplication.network.bean.ChangeResponseBean;
import com.endoc.phtotapplication.network.bean.IdList;
import com.endoc.phtotapplication.network.bean.PersonResponseBean;
import com.endoc.phtotapplication.network.bean.RequestBean;
import com.endoc.phtotapplication.network.bean.ResultBean;
import com.endoc.phtotapplication.network.bean.VerifyRequestBean;
import com.endoc.phtotapplication.network.retrofit.RetrofitClient;
import com.endoc.phtotapplication.utils.Base64Utils;
import com.endoc.phtotapplication.utils.BitMapUts;
import com.endoc.phtotapplication.utils.ComPressBitmapUtils;
import com.endoc.phtotapplication.utils.SharePrefrencesUtils;
import com.endoc.phtotapplication.utils.StringUtils;
import com.endoc.phtotapplication.utils.YUVutils;
import com.hikvision.face.HikFRAAPI;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WorkUtils {
    boolean isDebug =true;
   static WorkUtils workUtils =null;
  static Context mContext;
    public static WorkUtils getInstance(Context context){
        mContext = context;
        if(workUtils==null){
            synchronized (WorkUtils.class){
                if(workUtils==null){
                    workUtils =new WorkUtils();
                }
            }
        }
        return workUtils;
    }
    FaceInterface faceInterface = new RetrofitClient().faceInterface();
    String FaceApiURL = "http://58.33.107.234:1195/faceweb/";
    /**
     * 上传图片
     * @param person personID
     * @param device 设备id
     * @param base64   base64
     */
    public void startUpLoad(String person,String device,String base64){
        String tbAddress = (String)SharePrefrencesUtils.getParam(mContext, StringUtils.tbAddress, "");
        String deviceID = (String)SharePrefrencesUtils.getParam(mContext, StringUtils.deviceID, "");
        if(isDebug){
            tbAddress =FaceApiURL+"RecFaceRecordByAndroid.aspx";
        }else {//如果是正式版本
            device =deviceID;
            device =deviceID;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Call<ResultBean> verify = faceInterface.verify(new VerifyRequestBean("216", "192.168.100.200", simpleDateFormat.format(new Date()), imageToBase64("/sdcard/0.Jpeg")));
        //Call<ResultBean> verify = faceInterface.verify(new VerifyRequestBean(person, device, simpleDateFormat.format(new Date()), imageToBase64(path)));
        Date date = new Date();

        Call<ResultBean> verify = faceInterface.verify(tbAddress,new VerifyRequestBean(person, device, simpleDateFormat.format(date), base64));
        String finalDevice = device;
        verify.enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                Log.d("MyPhotoActivity","startUpLoad verify onResponse=="+response.body().getCode());
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
                Log.d("MyPhotoActivity","startUpLoad verify t=="+t.getMessage());

                // 没有的话上传失败保存起来
                UploadPerson uploadPerson = new UploadPerson();
                uploadPerson.setPerson(person);
                File file = new File(StringUtils.FilePersonUpload);
                if(!file.exists()){
                    file.mkdirs();
                }
                base64ToFile(base64, StringUtils.FilePersonUpload+ date.getTime() +".jpg");
                uploadPerson.setRepic(StringUtils.FilePersonUpload+ date.getTime() +".jpg");
                uploadPerson.setRetime(simpleDateFormat.format(date));//设置时间
                uploadPerson.setDevice(finalDevice);//设置deviceId
                uploadPerson.save();
            }
        });
    }



    /**
     * 上传图片,从失败数据库数据库中去上传
     */
    public void startUpLoadForFail(){
        String tbAddress = (String)SharePrefrencesUtils.getParam(mContext, StringUtils.tbAddress, "");
        if(isDebug){
            tbAddress =FaceApiURL+"RecFaceRecordByAndroid.aspx";
        }

        List<UploadPerson> all = LitePal.findAll(UploadPerson.class);
        for (int i=0;i<all.size();i++){
            UploadPerson uploadPerson = all.get(i);
            Call<ResultBean> verify = faceInterface.verify(tbAddress,new VerifyRequestBean(uploadPerson.getPerson(), uploadPerson.getDevice(), uploadPerson.getRetime(),imageToBase64(uploadPerson.getRepic())));
            verify.enqueue(new Callback<ResultBean>() {
                @Override
                public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                    Log.d("MyPhotoActivity","startUpLoadForFail verify onResponse=="+response.body().getCode());
                    //成功的话就删除此文件
                    File file =new File(uploadPerson.getRepic());
                    file.delete();
                    //再删除数据库记录
                    uploadPerson.delete();
                }

                @Override
                public void onFailure(Call<ResultBean> call, Throwable t) {
                    Log.d("MyPhotoActivity","startUpLoadForFail verify t=="+t.getMessage());
                }
            });
        }
    }




    Timer timer;
    class MyTimerTask extends  TimerTask{
        @Override
        public void run() {
          /*  changeData();
            if(true) {
                return;
            }*/
            //图片上传
  /*      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Call<ResultBean> verify = faceInterface.verify(new VerifyRequestBean("216", "192.168.100.200", simpleDateFormat.format(new Date()), imageToBase64("/sdcard/0.Jpeg")));
        verify.enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                Log.d("MyPhotoActivity","verify onResponse=="+response.body().getCode());
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
                Log.d("MyPhotoActivity","verify t=="+t.getMessage());
            }
        });*/
        /*String base64 = imageToBase64("/sdcard/0.Jpeg");
        base64ToFile(base64,"/sdcard/test0.Jpeg");*/

        //整个最简单的,如果当前时间在增量同步的时间误差内就执行,不用闹钟了
          /*  long zltb = (Long)SharePrefrencesUtils.getParam(mContext, StringUtils.zltb, (long)15000);
            Calendar qlCalendar = Calendar.getInstance();
            qlCalendar.set(Calendar.HOUR_OF_DAY, 0);
            qlCalendar.set(Calendar.SECOND, 0);
            qlCalendar.set(Calendar.MILLISECOND, 0);

            //如果当前时间减去设置的同步时间小于增量时间,那么就执行
           if(Calendar.getInstance().getTimeInMillis()-qlCalendar.getTimeInMillis()<zltb||Calendar.getInstance().getTimeInMillis()-qlCalendar.getTimeInMillis()<-zltb){

           }*/
/*
* 2020-10-21 20:38:55.545 26381-26455/? E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.endoc.phtotapplication, PID: 26381
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at com.endoc.phtotapplication.utils.SharePrefrencesUtils.getParam(SharePrefrencesUtils.java:52)
        at com.endoc.phtotapplication.WorkUtils$MyTimerTask.run(WorkUtils.java:198)
        at java.util.TimerThread.mainLoop(Timer.java:555)
        at java.util.TimerThread.run(Timer.java:505)
* */

            changeData();
            if(true){
                return;
            }

            String deviceID = (String)SharePrefrencesUtils.getParam(mContext, StringUtils.deviceID, "");

            long qltb = (Long) SharePrefrencesUtils.getParam(mContext, StringUtils.qltb, (long)21600);
            String recordAddress = (String)SharePrefrencesUtils.getParam(mContext, StringUtils.recordAddress, "");

            if(isDebug){
                recordAddress =FaceApiURL+"GetFaceByAndroidcs.aspx";
                deviceID ="192.168.100.200";
            }
            Log.d("MyPhotoActivity","recordAddress=="+recordAddress);
            RequestBean requestBean = new RequestBean(deviceID, "Change");
            Call<ChangeResponseBean> change = faceInterface.change(recordAddress,requestBean);
            String finalRecordAddress = recordAddress;
            String finalDeviceID = deviceID;
            change.enqueue(new Callback<ChangeResponseBean>() {
                @Override
                public void onResponse(Call<ChangeResponseBean> call, Response<ChangeResponseBean> response) {
                    Log.d("MyPhotoActivity","change onResponse=="+response.body().toString());
                    List<IdList> idList = response.body().getIdList();
                    if(idList.size()>0){//如果list有数据,那么进行详细数据请求操作

                        RequestBean requestPersonBean = new RequestBean(finalDeviceID, "Person");
                        for (int i=0;i<idList.size();i++){
                            //changeMy(idList,i,requestPersonBean,finalRecordAddress,finalDeviceID);
                            Log.d("MyPhotoActivity","type=="+idList.get(i).getChange());
                            Log.d("MyPhotoActivity","idlist==="+idList.get(i).getId());
                            //设置请求的类型
                            requestPersonBean.setReturnid(new RequestBean.ReturnidBean(idList.get(i).getId(),idList.get(i).getChange()));

                            if(idList.get(i).getChange().equals("Delete")){//如果是删除操作
                                //1.执行删除
                                //本地删除
                                List<Person> personList = LitePal.where("personID = ?", idList.get(i).getId()).find(Person.class);
                                if(personList.size()==0) {
                                    Log.d(TAG,"删除时本地没数据");
                                    continue;
                                }
                                for(int j=0;j<personList.size();j++){
                                    File file = new File(personList.get(j).getRepic());
                                    file.delete();
                                }

                                //2.数据库删除
                                LitePal.deleteAll(Person.class,"personID = ?",idList.get(i).getId());

                                //3.人脸库删除
                                mHikFRAAPI.faceDelModel("facetest",idList.get(i).getId(),idList.get(i).getId(),StringUtils.databasePath);

                                //2.告诉服务器删除成功
                                requestPersonBean.setReqType("Return");//直接返回,所以修改为Return
                                Call<ResultBean> addReturnBeanCall = faceInterface.addReturn(finalRecordAddress,requestPersonBean);
                                addReturnBeanCall.enqueue(new Callback<ResultBean>() {
                                    @Override
                                    public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                                        Log.d("MyPhotoActivity","deleteReturnBeanCall response=="+response.body().getCode());
                                    }

                                    @Override
                                    public void onFailure(Call<ResultBean> call, Throwable t) {
                                        Log.d("MyPhotoActivity","deleteReturnBeanCall t=="+t.getMessage());
                                    }
                                });

                                //3.然后终止此次循环
                                continue;
                            }


                            //如果是Add或者是modify,那么就需要PersonId参数,即ReqType为Person的时候就需要这个id
                            requestPersonBean.setPersonId(idList.get(i).getId());
                            Call<PersonResponseBean> person = faceInterface.person(finalRecordAddress,requestPersonBean);

                            person.enqueue(new Callback<PersonResponseBean>() {
                                @Override
                                public void onResponse(Call<PersonResponseBean> call, Response<PersonResponseBean> response) {

                                    Log.d("MyPhotoActivity","person response=="+response.body().getCode());
                                    if(response.body().getPerson().getId().isEmpty()){
                                        //Toast.makeText(mContext,"此id为空",Toast.LENGTH_SHORT).show();
                                        Log.d(TAG,"此id为空");
                                    }
                                    if(response.body().getPerson().getVdatetime().isEmpty()){
                                        //Toast.makeText(mContext,"此时间为空",Toast.LENGTH_SHORT).show();
                                        Log.d(TAG,"此时间为空");
                                    }
                                    //Environment.getExternalStorageDirectory().getPath()

                                   /* //转为yuv
                                    Log.d(TAG,"缩放之前");
                                    //先缩放
                                    Bitmap bitmap = Base64Utils.base64ToBitmap(response.body().getPerson().getPicBase64());
                                    Log.d(TAG,"缩放");
                                    //设置出640*480的图片
                                    Bitmap resizeBitmap = BitMapUts.zoomBitmap(bitmap, mWidth, mHeight);
                                    //resizeBitmap width==640    height===480
                                    Log.d(TAG,"resizeBitmap width=="+resizeBitmap.getWidth()+"    height==="+resizeBitmap.getHeight());

                                    String bitmapToBase64 = Base64Utils.bitmapToBase64(resizeBitmap);


                                        //base64转byte[]
                                        //decode = java.util.Base64.getDecoder().decode(bitmapToBase64);
                                    byte[]    decode  = Base64.decode(bitmapToBase64,Base64.DEFAULT);//转换为2进制
                                    Log.d(TAG,"decode size=="+decode.length);
                                        //Base64Utils.savebitmap(Base64Utils.getBitmapFromByte(decode));转换为2进制的数可以成功解析
                                    Base64Utils.savebitmap(resizeBitmap);
                                    //byte[]  addYuvData = new byte[640 * 480 * 3 / 2];
                                    byte[] bitmapByte = Base64Utils.getBitmapByte(resizeBitmap);
                                    byte[]  addYuvData = new byte[bitmapByte.length* 3 / 2];
                                    Log.d(TAG,"bitmapByte size=="+bitmapByte.length);
                                    Log.d(TAG,"addYuvData size=="+addYuvData.length);
                                    YUV420spRotate180(addYuvData,bitmapByte,mWidth,mHeight);*/
                                    //decodeYUV420SP(addYuvData,bitmapByte,mWidth,mHeight);
                                    //加载人脸图片
                                    Bitmap bitmap = Base64Utils.base64ToBitmap(response.body().getPerson().getPicBase64());
                                    //Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/facelib/62.jpg");
                                   /* Matrix matrix = new Matrix();
                                    //旋转270度
                                    matrix.postRotate(270);
                                    Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);*/
                                    //缩放为算法初始化指定的宽高 例如640*480
                                    byte[] bytes = ComPressBitmapUtils.zoomImage(bitmap, 640, 480);
                                    //宽高互换
                                    //byte[] bytes = ComPressBitmapUtils.zoomImage(bitmap, 480, 640);

                                    //将缩放后的byte转为图片
                                    Bitmap tempBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                                    //将转换后图片转为yuv数据
                                    byte[] yuvByBitmap = YUVutils.getYUVByBitmap(tempBitmap);
                                    Log.d(TAG,"yuvByBitmap size==="+yuvByBitmap.length);
                                    String facePath =  StringUtils.FilePath+ response.body().getPerson().getId() +".jpg";
                                    //Base64Utils.getFile(yuvByBitmap,StringUtils.FilePath,"test4.yuv");

                                    Bitmap capBm = nv21ToBitmap(yuvByBitmap, mWidth, mHeight);
                                    Matrix matrix = new Matrix();
                                    matrix.postRotate((0));
                                    Log.i(TAG, "addFaceModel: "+capBm);

                                    Bitmap rotatedBitmap = Bitmap.createBitmap(capBm, 0, 0, capBm.getWidth(), capBm.getHeight(), matrix, true);
                                    try {
                                        OutputStream out = new FileOutputStream(facePath);
                                        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    }

                                    //直接保存为
                                    //Base64Utils.getFile(yuvByBitmap,StringUtils.FilePath,response.body().getPerson().getId() +".yuv");

                                    Person litpalPerson = new Person();
                                    litpalPerson.setRetime(response.body().getPerson().getVdatetime());
                                    litpalPerson.setName(response.body().getPerson().getName());
                                    litpalPerson.setPersonID(response.body().getPerson().getId());
                                    litpalPerson.setMembertype(response.body().getPerson().getMembertype());

                                    //保存路径
                                    litpalPerson.setRepic(facePath);
                                    //如果有就更新,没有就保存
                                    litpalPerson.saveOrUpdate("personID = ?",response.body().getPerson().getId());
                                    //  String facePath = "/sdcard/facelib/" + humId + ".jpg";
                                    //                                mCamHandle.addFaceModel("facetest", humId, humId, facePath, "/sdcard/facelib/database.bin");
                                    //添加人脸到识别库
                                    //新建一个BASE64Decoder

                                    int init = mHikFRAAPI.init(640, 480, HikFRAAPI.YUV_FORMAT.YUV_NV21, "/sdcard/DFR_Model.bin");
                                    Log.i(TAG, "初始化结果. : " + init);

                                        //添加图片的时候设置为0度
                                        int param = mHikFRAAPI.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_0);
                                        Log.i(TAG, "设置角度. : " + param+"     添加的id是==="+response.body().getPerson().getId());
                                        int facetest = mHikFRAAPI.faceAddModel("facetest", response.body().getPerson().getId(), response.body().getPerson().getId(), facePath, StringUtils.databasePath);
                                        Log.d(TAG, "添加的结果===" + facetest);

                                        //添加完图片设置270
                                        mHikFRAAPI.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_270);

                                    //本地数据存储成功之后,执行返回操作
                                    RequestBean addReturnBean = new RequestBean(finalDeviceID, "Return");
                                    addReturnBean.setReturnid(new RequestBean.ReturnidBean(response.body().getPerson().getId(),"Add"));
                                    Call<ResultBean> addReturnBeanCall = faceInterface.addReturn(finalRecordAddress,addReturnBean);
                                    addReturnBeanCall.enqueue(new Callback<ResultBean>() {
                                        @Override
                                        public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                                            Log.d("MyPhotoActivity","addReturnBeanCall response=="+response.body().getCode());
                                        }

                                        @Override
                                        public void onFailure(Call<ResultBean> call, Throwable t) {
                                            Log.d("MyPhotoActivity","addReturnBeanCall t=="+t.getMessage());
                                        }
                                    });

                                    //byte[] decode = Base64.decode(response.body().getPerson().getPicBase64().getBytes(), Base64.DEFAULT);
                                }

                                @Override
                                public void onFailure(Call<PersonResponseBean> call, Throwable t) {
                                    Log.d("MyPhotoActivity","person onFailure=="+t.getMessage());
                                }
                            });
                        }
                    }
                }

                @Override
                public void onFailure(Call<ChangeResponseBean> call, Throwable t) {
                    Log.d("MyPhotoActivity","onFailure=="+t.getMessage());
                }
            });
        }

    }


   /* public void changeMy( List<IdList> idList,  int i, RequestBean requestPersonBean,String finalRecordAddress,String finalDeviceID){
        {
            if(i>=idList.size()){
                return;
            }
            Log.d("MyPhotoActivity","type=="+idList.get(i).getChange());
            Log.d("MyPhotoActivity","idlist==="+idList.get(i).getId());
            //设置请求的类型
            requestPersonBean.setReturnid(new RequestBean.ReturnidBean(idList.get(i).getId(),idList.get(i).getChange()));

            if(idList.get(i).getChange().equals("Delete")){//如果是删除操作
                //1.执行删除
                //本地删除
                List<Person> personList = LitePal.where("personID = ?", idList.get(i).getId()).find(Person.class);
                if(personList.size()==0) {
                    Log.d(TAG,"删除时本地没数据");
                    i++;
                    changeMy(idList,i,requestPersonBean,finalRecordAddress,finalDeviceID);
                    return;
                }
                for(int j=0;j<personList.size();j++){
                    File file = new File(personList.get(j).getRepic());
                    file.delete();
                }

                //2.数据库删除
                LitePal.deleteAll(Person.class,"personID = ?",idList.get(i).getId());

                //3.人脸库删除
                mHikFRAAPI.faceDelModel("facetest",idList.get(i).getId(),idList.get(i).getId(),StringUtils.databasePath);

                //2.告诉服务器删除成功
                requestPersonBean.setReqType("Return");//直接返回,所以修改为Return
                Call<ResultBean> addReturnBeanCall = faceInterface.addReturn(finalRecordAddress,requestPersonBean);
                addReturnBeanCall.enqueue(new Callback<ResultBean>() {
                    @Override
                    public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                        Log.d("MyPhotoActivity","deleteReturnBeanCall response=="+response.body().getCode());
                        i++;
                        changeMy(idList,i,requestPersonBean,finalRecordAddress,finalDeviceID);
                        return;
                    }

                    @Override
                    public void onFailure(Call<ResultBean> call, Throwable t) {
                        Log.d("MyPhotoActivity","deleteReturnBeanCall t=="+t.getMessage());
                        i++;
                        changeMy(idList,i,requestPersonBean,finalRecordAddress,finalDeviceID);
                        return;
                    }
                });

                //3.然后终止此次循环
                return;
            }


            //如果是Add或者是modify,那么就需要PersonId参数,即ReqType为Person的时候就需要这个id
            requestPersonBean.setPersonId(idList.get(i).getId());
            Call<PersonResponseBean> person = faceInterface.person(finalRecordAddress,requestPersonBean);

            person.enqueue(new Callback<PersonResponseBean>() {
                @Override
                public void onResponse(Call<PersonResponseBean> call, Response<PersonResponseBean> response) {

                    Log.d("MyPhotoActivity","person response=="+response.body().getCode());
                    if(response.body().getPerson().getId().isEmpty()){
                        //Toast.makeText(mContext,"此id为空",Toast.LENGTH_SHORT).show();
                        Log.d(TAG,"此id为空");
                    }
                    if(response.body().getPerson().getVdatetime().isEmpty()){
                        //Toast.makeText(mContext,"此时间为空",Toast.LENGTH_SHORT).show();
                        Log.d(TAG,"此时间为空");
                    }
                    //Environment.getExternalStorageDirectory().getPath()

                                   *//* //转为yuv
                                    Log.d(TAG,"缩放之前");
                                    //先缩放
                                    Bitmap bitmap = Base64Utils.base64ToBitmap(response.body().getPerson().getPicBase64());
                                    Log.d(TAG,"缩放");
                                    //设置出640*480的图片
                                    Bitmap resizeBitmap = BitMapUts.zoomBitmap(bitmap, mWidth, mHeight);
                                    //resizeBitmap width==640    height===480
                                    Log.d(TAG,"resizeBitmap width=="+resizeBitmap.getWidth()+"    height==="+resizeBitmap.getHeight());

                                    String bitmapToBase64 = Base64Utils.bitmapToBase64(resizeBitmap);


                                        //base64转byte[]
                                        //decode = java.util.Base64.getDecoder().decode(bitmapToBase64);
                                    byte[]    decode  = Base64.decode(bitmapToBase64,Base64.DEFAULT);//转换为2进制
                                    Log.d(TAG,"decode size=="+decode.length);
                                        //Base64Utils.savebitmap(Base64Utils.getBitmapFromByte(decode));转换为2进制的数可以成功解析
                                    Base64Utils.savebitmap(resizeBitmap);
                                    //byte[]  addYuvData = new byte[640 * 480 * 3 / 2];
                                    byte[] bitmapByte = Base64Utils.getBitmapByte(resizeBitmap);
                                    byte[]  addYuvData = new byte[bitmapByte.length* 3 / 2];
                                    Log.d(TAG,"bitmapByte size=="+bitmapByte.length);
                                    Log.d(TAG,"addYuvData size=="+addYuvData.length);
                                    YUV420spRotate180(addYuvData,bitmapByte,mWidth,mHeight);*//*
                    //decodeYUV420SP(addYuvData,bitmapByte,mWidth,mHeight);
                    //加载人脸图片
                    Bitmap bitmap = Base64Utils.base64ToBitmap(response.body().getPerson().getPicBase64());
                    //Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/facelib/62.jpg");
                                   *//* Matrix matrix = new Matrix();
                                    //旋转270度
                                    matrix.postRotate(270);
                                    Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);*//*
                    //缩放为算法初始化指定的宽高 例如640*480
                    byte[] bytes = ComPressBitmapUtils.zoomImage(bitmap, 640, 480);
                    //宽高互换
                    //byte[] bytes = ComPressBitmapUtils.zoomImage(bitmap, 480, 640);

                    //将缩放后的byte转为图片
                    Bitmap tempBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    //将转换后图片转为yuv数据
                    byte[] yuvByBitmap = YUVutils.getYUVByBitmap(tempBitmap);
                    Log.d(TAG,"yuvByBitmap size==="+yuvByBitmap.length);
                    String facePath =  StringUtils.FilePath+ response.body().getPerson().getId() +".jpg";
                    //Base64Utils.getFile(yuvByBitmap,StringUtils.FilePath,"test4.yuv");

                    Bitmap capBm = nv21ToBitmap(yuvByBitmap, mWidth, mHeight);
                    Matrix matrix = new Matrix();
                    matrix.postRotate((0));
                    Log.i(TAG, "addFaceModel: "+capBm);

                    Bitmap rotatedBitmap = Bitmap.createBitmap(capBm, 0, 0, capBm.getWidth(), capBm.getHeight(), matrix, true);
                    try {
                        OutputStream out = new FileOutputStream(facePath);
                        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                    //直接保存为
                    //Base64Utils.getFile(yuvByBitmap,StringUtils.FilePath,response.body().getPerson().getId() +".yuv");

                    Person litpalPerson = new Person();
                    litpalPerson.setRetime(response.body().getPerson().getVdatetime());
                    litpalPerson.setName(response.body().getPerson().getName());
                    litpalPerson.setPersonID(response.body().getPerson().getId());
                    litpalPerson.setMembertype(response.body().getPerson().getMembertype());

                    //保存路径
                    litpalPerson.setRepic(facePath);
                    //如果有就更新,没有就保存
                    litpalPerson.saveOrUpdate("personID = ?",response.body().getPerson().getId());
                    //  String facePath = "/sdcard/facelib/" + humId + ".jpg";
                    //                                mCamHandle.addFaceModel("facetest", humId, humId, facePath, "/sdcard/facelib/database.bin");
                    //添加人脸到识别库
                    //新建一个BASE64Decoder

                    int init = mHikFRAAPI.init(640, 480, HikFRAAPI.YUV_FORMAT.YUV_NV21, "/sdcard/DFR_Model.bin");
                    Log.i(TAG, "初始化结果. : " + init);
                    synchronized (WorkUtils.class) {
                        //添加图片的时候设置为0度
                        int param = mHikFRAAPI.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_0);
                        Log.i(TAG, "设置角度. : " + param+"     添加的id是==="+response.body().getPerson().getId());
                        int facetest = mHikFRAAPI.faceAddModel("facetest", response.body().getPerson().getId(), response.body().getPerson().getId(), facePath, StringUtils.databasePath);
                        Log.d(TAG, "添加的结果===" + facetest);

                        //添加完图片设置270
                        mHikFRAAPI.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_270);
                    }
                    //本地数据存储成功之后,执行返回操作
                    RequestBean addReturnBean = new RequestBean(finalDeviceID, "Return");
                    addReturnBean.setReturnid(new RequestBean.ReturnidBean(response.body().getPerson().getId(),"Add"));
                    Call<ResultBean> addReturnBeanCall = faceInterface.addReturn(finalRecordAddress,addReturnBean);
                    addReturnBeanCall.enqueue(new Callback<ResultBean>() {
                        @Override
                        public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                            Log.d("MyPhotoActivity","addReturnBeanCall response=="+response.body().getCode());
                            i++;
                            changeMy(idList,i,requestPersonBean,finalRecordAddress,finalDeviceID);
                            return;
                        }

                        @Override
                        public void onFailure(Call<ResultBean> call, Throwable t) {
                            Log.d("MyPhotoActivity","addReturnBeanCall t=="+t.getMessage());
                            i++;
                            changeMy(idList,i,requestPersonBean,finalRecordAddress,finalDeviceID);
                            return;
                        }
                    });

                    //byte[] decode = Base64.decode(response.body().getPerson().getPicBase64().getBytes(), Base64.DEFAULT);
                }

                @Override
                public void onFailure(Call<PersonResponseBean> call, Throwable t) {
                    Log.d("MyPhotoActivity","person onFailure=="+t.getMessage());
                    i++;
                    changeMy(idList,i,requestPersonBean,finalRecordAddress,finalDeviceID);
                    return;
                }
            });
        }
    }*/
    boolean isChangeData =false;//是否在请求
    int i=0;
    public void changeData(){
        if(isChangeData==true){
            return;
        }
        isChangeData =true;
        i=0;
        String deviceID = (String)SharePrefrencesUtils.getParam(mContext, StringUtils.deviceID, "");
        long qltb = (Long) SharePrefrencesUtils.getParam(mContext, StringUtils.qltb, (long)21600);
        String recordAddress = (String)SharePrefrencesUtils.getParam(mContext, StringUtils.recordAddress, "");

        if(isDebug){
            recordAddress =FaceApiURL+"GetFaceByAndroidcs.aspx";
            deviceID ="192.168.100.200";
        }
        Log.d("MyPhotoActivity","recordAddress=="+recordAddress);
        RequestBean requestBean = new RequestBean(deviceID, "Change");
        String finalRecordAddress = recordAddress;
        String finalDeviceID = deviceID;

        //Call<ChangeResponseBean> change = faceInterface.change(recordAddress,requestBean);

        faceInterface.change3(FaceApiURL + "GetFaceByAndroidcs.aspx", requestBean).subscribe(new Observer<ChangeResponseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ChangeResponseBean changeResponseBean) {
                Log.d("MyPhotoActivity","change onResponse=="+changeResponseBean.getIdList().size());
                int changeResponseBeanSize = changeResponseBean.getIdList().size();
                PublishSubject<IdList> idListPublishSubject =PublishSubject.create();
                idListPublishSubject.subscribe(new Observer<IdList>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(IdList idList) {
                     /*   List<IdList> idList = response.body().getIdList();
                        if(idList.size()>0){//如果list有数据,那么进行详细数据请求操作*/

                            RequestBean requestPersonBean = new RequestBean(finalDeviceID, "Person");
                           // for (int i=0;i<idList.size();i++){

                                Log.d("MyPhotoActivity","type=="+idList.getChange());
                                Log.d("MyPhotoActivity","idlist==="+idList.getId());
                                //设置请求的类型
                                requestPersonBean.setReturnid(new RequestBean.ReturnidBean(idList.getId(),idList.getChange()));

                                if(idList.getChange().equals("Delete")){//如果是删除操作
                                    //1.执行删除
                                    //本地删除
                                    List<Person> personList = LitePal.where("personID = ?", idList.getId()).find(Person.class);
                                    if(personList.size()!=0) {

                                     /*   if(i<changeResponseBeanSize-1){
                                            i++;
                                           idListPublishSubject.onNext(changeResponseBean.getIdList().get(i));
                                        }
                                        return;*/

                                    for(int j=0;j<personList.size();j++){
                                        File file = new File(personList.get(j).getRepic());
                                        file.delete();
                                    }

                                    //2.数据库删除
                                    LitePal.deleteAll(Person.class,"personID = ?",idList.getId());

                                    //3.人脸库删除
                                    mHikFRAAPI.faceDelModel("facetest",idList.getId(),idList.getId(),StringUtils.databasePath);
                                    }else {
                                        Log.d(TAG,"删除时本地没数据");
                                    }
                                    //2.告诉服务器删除成功
                                    requestPersonBean.setReqType("Return");//直接返回,所以修改为Return
                                    Call<ResultBean> addReturnBeanCall = faceInterface.addReturn(finalRecordAddress,requestPersonBean);
                                    addReturnBeanCall.enqueue(new Callback<ResultBean>() {
                                        @Override
                                        public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                                            Log.d("MyPhotoActivity","deleteReturnBeanCall response=="+response.body().getCode());
                                            if(i<changeResponseBeanSize-1){
                                                i++;
                                                idListPublishSubject.onNext(changeResponseBean.getIdList().get(i));
                                            }else {
                                                isChangeData=false;
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<ResultBean> call, Throwable t) {
                                            Log.d("MyPhotoActivity","deleteReturnBeanCall t=="+t.getMessage());
                                            if(i<changeResponseBeanSize-1){
                                                i++;
                                                idListPublishSubject.onNext(changeResponseBean.getIdList().get(i));
                                            } else {
                                                isChangeData=false;
                                            }
                                        }
                                    });

                                    //3.然后终止此次循环
                                    return;
                                }


                                //如果是Add或者是modify,那么就需要PersonId参数,即ReqType为Person的时候就需要这个id
                                requestPersonBean.setPersonId(idList.getId());
                                Call<PersonResponseBean> person = faceInterface.person(finalRecordAddress,requestPersonBean);

                                person.enqueue(new Callback<PersonResponseBean>() {
                                    @Override
                                    public void onResponse(Call<PersonResponseBean> call, Response<PersonResponseBean> response) {

                                        Log.d("MyPhotoActivity","person response=="+response.body().getCode());
                                        if(response.body().getPerson().getId().isEmpty()){
                                            //Toast.makeText(mContext,"此id为空",Toast.LENGTH_SHORT).show();
                                            Log.d(TAG,"此id为空");
                                        }
                                        if(response.body().getPerson().getVdatetime().isEmpty()){
                                            //Toast.makeText(mContext,"此时间为空",Toast.LENGTH_SHORT).show();
                                            Log.d(TAG,"此时间为空");
                                        }

                                        //加载人脸图片
                                        Bitmap bitmap = Base64Utils.base64ToBitmap(response.body().getPerson().getPicBase64());

                                        //缩放为算法初始化指定的宽高 例如640*480
                                        //byte[] bytes = ComPressBitmapUtils.zoomImage(bitmap, 472, 354);
                                        //此方法宽高参数标记反了
                                        byte[] bytes = ComPressBitmapUtils.zoomImage(bitmap, 480, 640);
                                        //宽高互换
                                        //byte[] bytes = ComPressBitmapUtils.zoomImage(bitmap, 480, 640);

                                        //将缩放后的byte转为图片
                                        Bitmap tempBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                                        //将转换后图片转为yuv数据
                                        //byte[] yuvByBitmap = YUVutils.getYUVByBitmap(tempBitmap);
                                        //Log.d(TAG,"yuvByBitmap size==="+yuvByBitmap.length);
                                        String facePath =  StringUtils.FilePath+ response.body().getPerson().getId() +".jpg";
                                        //Base64Utils.getFile(yuvByBitmap,StringUtils.FilePath,"test4.yuv");

                                        //Bitmap capBm = nv21ToBitmap(yuvByBitmap, mWidth, mHeight);
                                        Matrix matrix = new Matrix();
                                       // matrix.postRotate((0));
                                        //Log.i(TAG, "addFaceModel: "+capBm);

                                        //Bitmap rotatedBitmap = Bitmap.createBitmap(capBm, 0, 0, capBm.getWidth(), capBm.getHeight(), matrix, true);
                                       Log.d(TAG,"宽为==="+tempBitmap.getWidth() +"高为==="+tempBitmap.getHeight());
                                        Bitmap rotatedBitmap = Bitmap.createBitmap(tempBitmap, 0, 0, tempBitmap.getWidth(), tempBitmap.getHeight(), matrix, true);
                                        try {
                                            OutputStream out = new FileOutputStream(facePath);
                                            rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                                        } catch (FileNotFoundException e) {
                                            e.printStackTrace();
                                        }

                                        //直接保存为
                                        //Base64Utils.getFile(yuvByBitmap,StringUtils.FilePath,response.body().getPerson().getId() +".yuv");

                                        Person litpalPerson = new Person();
                                        litpalPerson.setRetime(response.body().getPerson().getVdatetime());
                                        litpalPerson.setName(response.body().getPerson().getName());
                                        litpalPerson.setPersonID(response.body().getPerson().getId());
                                        litpalPerson.setMembertype(response.body().getPerson().getMembertype());

                                        //保存路径
                                        litpalPerson.setRepic(facePath);
                                        //如果有就更新,没有就保存
                                        litpalPerson.saveOrUpdate("personID = ?",response.body().getPerson().getId());
                                        //  String facePath = "/sdcard/facelib/" + humId + ".jpg";
                                        //                                mCamHandle.addFaceModel("facetest", humId, humId, facePath, "/sdcard/facelib/database.bin");
                                        //添加人脸到识别库
                                        //新建一个BASE64Decoder

                                        /*int init = mHikFRAAPI.init(640, 480, HikFRAAPI.YUV_FORMAT.YUV_NV21, "/sdcard/DFR_Model.bin");
                                        Log.i(TAG, "初始化结果. : " + init);*/
                                        //synchronized (WorkUtils.class) {
                                            //添加图片的时候设置为0度
                                            int param = mHikFRAAPI.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_0);
                                            Log.i(TAG, "设置角度. : " + param);
                                            int facetest = mHikFRAAPI.faceAddModel("facetest", response.body().getPerson().getId(), response.body().getPerson().getId(), facePath, StringUtils.databasePath);
                                            Log.d(TAG, "添加的id是==="+response.body().getPerson().getId()+"    添加的结果===" + facetest);
                                            if(facetest!=0) {
                                                SharePrefrencesUtils.setParam(mContext, StringUtils.addFail, (String) SharePrefrencesUtils.getParam(mContext, StringUtils.addFail, "") +","+ response.body().getPerson().getId());
                                                //如果添加失败,那么就不上传添加的
                                               /* if(i<changeResponseBeanSize-1){
                                                    i++;
                                                    idListPublishSubject.onNext(changeResponseBean.getIdList().get(i));
                                                }else {
                                                    isChangeData=false;
                                                }*/
                                            }
                                            //添加完图片设置270
                                            mHikFRAAPI.setParam(HikFRAAPI.FRA_SET_KEY.FRA_KEY_ROTATION, HikFRAAPI.ROTATION_ANGLE.ROTATION_270);
                                        //}
                                        //本地数据存储成功之后,执行返回操作
                                        RequestBean addReturnBean = new RequestBean(finalDeviceID, "Return");
                                        addReturnBean.setReturnid(new RequestBean.ReturnidBean(response.body().getPerson().getId(),"Add"));
                                        Call<ResultBean> addReturnBeanCall = faceInterface.addReturn(finalRecordAddress,addReturnBean);
                                        addReturnBeanCall.enqueue(new Callback<ResultBean>() {
                                            @Override
                                            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                                                Log.d("MyPhotoActivity","addReturnBeanCall response=="+response.body().getCode());
                                                if(i<changeResponseBeanSize-1){
                                                    i++;
                                                    idListPublishSubject.onNext(changeResponseBean.getIdList().get(i));
                                                }else {
                                                    isChangeData=false;
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResultBean> call, Throwable t) {
                                                Log.d("MyPhotoActivity","addReturnBeanCall t=="+t.getMessage());
                                                if(i<changeResponseBeanSize-1){
                                                    i++;
                                                    idListPublishSubject.onNext(changeResponseBean.getIdList().get(i));
                                                }else {
                                                    isChangeData=false;
                                                }
                                            }
                                        });

                                        //byte[] decode = Base64.decode(response.body().getPerson().getPicBase64().getBytes(), Base64.DEFAULT);
                                    }

                                    @Override
                                    public void onFailure(Call<PersonResponseBean> call, Throwable t) {
                                        Log.d("MyPhotoActivity","person onFailure=="+t.getMessage());
                                        if(i<changeResponseBeanSize-1){
                                            i++;
                                            idListPublishSubject.onNext(changeResponseBean.getIdList().get(i));
                                        }else {
                                            isChangeData=false;
                                        }
                                    }
                                });
                            }


                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
                if(changeResponseBeanSize!=0) {
                    idListPublishSubject.onNext(changeResponseBean.getIdList().get(0));
                }else {
                    isChangeData=false;
                }
            }



            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });



    }


    private Type.Builder yuvType, rgbaType;
    private RenderScript rs;
    private Allocation in, out;
    private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic;
    public Bitmap nv21ToBitmap(byte[] nv21, int width, int height) {
        rs = RenderScript.create(BaseApplication.getContext());
        yuvType = new Type.Builder(rs, Element.U8(rs)).setX(nv21.length);
        yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
        in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);

        rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
        out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);

        in.copyFrom(nv21);
        yuvToRgbIntrinsic.setInput(in);
        yuvToRgbIntrinsic.forEach(out);
        Bitmap bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        out.copyTo(bmpout);
        return bmpout;

    }
    String TAG="MyPhotoActivity";

    private int mWidth = 640;
    private int mHeight = 480;



    HikFRAAPI mHikFRAAPI;
    public void startTimer(HikFRAAPI hikFRAAPI){
        mHikFRAAPI =hikFRAAPI;
        timer= new Timer();
        long zltb = (Long)SharePrefrencesUtils.getParam(mContext, StringUtils.zltb, (long)15000);
        if(isDebug){
            zltb =60000;
        }
        timer.schedule(new MyTimerTask(),0,zltb);
    }

    public void stopTimer(){
        if(timer!=null){
        timer.cancel();
        timer=null;
        }
        mHikFRAAPI =null;
        mContext = null;
    }




    /**
     * @param base64Str base64字符串
     * @param path  储存的路径
     * @return
     */
    public  boolean base64ToFile(String base64Str,String path) {
        byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);
        for (int i = 0; i < data.length; i++) {
            if(data[i] < 0){
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * @param path 图片路径
     * @return  base64编码
     */
    public  String imageToBase64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.NO_CLOSE);
         /*   try {
                //writeOcrStrtoFile(result,Environment.getExternalStorageDirectory() + "/" + StringData.casePath ,"baseImage.txt");
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            //生成本地文件测试
            //base64ToFile(result,"/sdcard/test0.jpg");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 保存文件到本地
     */
    public  void writeOcrStrtoFile(String result, String outPath, String outFileName) throws Exception {
        File dir = new File(outPath);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        File txt = new File(outPath + "/" + outFileName);
        if (!txt.exists()) {
            txt.createNewFile();
        }
        byte bytes[] = new byte[512];
        bytes = result.getBytes("US-ASCII");
        int b = bytes.length; // 是字节的长度，不是字符串的长度
        FileOutputStream fos = new FileOutputStream(txt);
//		fos.write(bytes, 0, b);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }


    public void YUV420spRotate180(byte[] des, byte[] src, int width, int height) {
        int n = 0;
        int uh = height >> 1;
        int wh = width * height;
        //copy y
        for (int j = height - 1; j >= 0; j--) {
            for (int i = width - 1; i >= 0; i--) {
                des[n++] = src[width * j + i];
            }
        }
        for (int j = uh - 1; j >= 0; j--) {
            for (int i = width - 1; i > 0; i -= 2) {
                des[n] = src[wh + width * j + i - 1];
                des[n + 1] = src[wh + width * j + i];
                n += 2;
            }
        }
    }


    public static void decodeYUV420SP(byte[] rgbBuf, byte[] yuv420sp,
                                      int width, int height) {

        final int frameSize = width * height;
        if (rgbBuf == null)

            throw new NullPointerException("buffer 'rgbBuf' is null");
        if (rgbBuf.length < frameSize * 3)

            throw new IllegalArgumentException("buffer 'rgbBuf' size "
                    + rgbBuf.length + " < minimum " + frameSize * 3);

        if (yuv420sp == null)

            throw new NullPointerException("buffer 'yuv420sp' is null");

        if (yuv420sp.length < frameSize * 3 / 2)

            throw new IllegalArgumentException("buffer 'yuv420sp' size "
                    + yuv420sp.length + " < minimum " + frameSize * 3 / 2);

        int i = 0, y = 0;

        int uvp = 0, u = 0, v = 0;

        int y1192 = 0, r = 0, g = 0, b = 0;

        for (int j = 0, yp = 0; j < height; j++) {
            uvp = frameSize + (j >> 1) * width;
            u = 0;
            v = 0;

            for (i = 0; i < width; i++, yp++) {
                y = (0xff & ((int) yuv420sp[yp])) - 16;

                if (y < 0)
                    y = 0;

                if ((i & 1) == 0) {
                    v = (0xff & yuv420sp[uvp++]) - 128;
                    u = (0xff & yuv420sp[uvp++]) - 128;
                }

                y1192 = 1192 * y;
                r = (y1192 + 1634 * v);
                g = (y1192 - 833 * v - 400 * u);
                b = (y1192 + 2066 * u);

                if (r < 0)
                    r = 0;
                else if (r > 262143)
                    r = 262143;

                if (g < 0)
                    g = 0;
                else if (g > 262143)
                    g = 262143;

                if (b < 0)
                    b = 0;
                else if (b > 262143)
                    b = 262143;

                rgbBuf[yp * 3] = (byte) (r >> 10);
                rgbBuf[yp * 3 + 1] = (byte) (g >> 10);
                rgbBuf[yp * 3 + 2] = (byte) (b >> 10);
            }
        }
    }



}
